package tech.summerly.weather.data

import tech.summerly.weather.data.bean.Forecast
import tech.summerly.weather.data.bean.RealTime
import tech.summerly.weather.data.local.WeatherCache
import tech.summerly.weather.data.remote.CaiYunService
import tech.summerly.weather.model.Region
import java.io.IOException

object WeatherRepository {

    /**
     *
     * 获取指定区域的实时天气
     *
     * @param region 区域
     * @param forceRefresh false 如果缓存中有可用的天气信息,则不会连接网络获取
     *                     true 强制从服务器获取天气信息
     */
    @Throws(IOException::class)
    suspend fun getRealtimeWeather(region: Region, forceRefresh: Boolean = false): RealTime {
        if (forceRefresh) {
            val cache = WeatherCache.getRealtimeWeather(region)
            if (cache != null) {
                return cache
            }
        }
        val realtime = CaiYunService.getRealtimeWeather(region.position)
        WeatherCache.refreshRealtimeWeather(region, realtime)
        realtime.region = region
        return realtime
    }

    @Throws(IOException::class)
    suspend fun getForecastWeather(region: Region, forceRefresh: Boolean = false): Forecast {
        if (forceRefresh) {
            val cache = WeatherCache.getForecastWeather(region)
            if (cache != null) {
                return cache
            }
        }
        return CaiYunService.getForecastWeather(region.position).also {
            WeatherCache.refreshWeatherForecast(region, it)
        }
    }

}